<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :init-param="initParam">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')"> 新增 </el-button>
        <el-button type="primary" :icon="Download" plain @click="downloadFile">导出数据</el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
      </template>
    </ProTable>
    <EvaluateDrawer ref="drawerRef" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, computed, onMounted } from "vue";
import { ExportObj, Performance } from "@/api/types/base";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import EvaluateDrawer from "./evaluateDrawer.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, View, Download } from "@element-plus/icons-vue";
import apiService from "@/api/services/apiService";
import { enumRender, monthRender, userRender } from "@/hooks/useColumnRender";
import { ExportColType } from "@/enums/sysEnum";
import { ElMessageBox } from "element-plus";
import { useDownload } from "@/hooks/useDownload";
import { useDateFormat } from "@vueuse/core";
import { useDataStore } from "@/stores/modules/data";

const initVar = reactive({
  tbName: "performance",
  tbCnName: "绩效评估"
});

const defaultDate = ref<Date>();
let curDate = new Date();
let [year, month] = [curDate.getFullYear(), curDate.getMonth()];
defaultDate.value = new Date(year, month - 1, 1);

// ProTable 实例
const proTable = ref<ProTableInstance>();
const dataStore = useDataStore();

const initParam = reactive({
  condition: {},
  options: { sort: { orgId: 1, avgScore: -1, level: 1 } }
});

const getTableList = async (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  if (newParams.condition && newParams.condition.performanceDate) {
    let curDate = new Date(newParams.condition.performanceDate);
    let [year, month] = [curDate.getFullYear(), curDate.getMonth()];
    let startDate = new Date(year, month, 1);
    let endDate = new Date(year, month + 1, 0, 23, 59, 59);
    newParams.condition.performanceDate = { $gte: startDate, $lte: endDate };
  }
  if (newParams.condition && newParams.condition.orgId) {
    newParams.condition.orgId = newParams.condition.orgId[newParams.condition.orgId.length - 1];
  }
  return apiService.findPage(initVar.tbName, newParams.condition, newParams.options);
};

const isOrNotList = computed(() => dataStore.getEnumByCsName("IS_NOT"));
const orgTree = computed(() => dataStore.orgTree);
const userList = computed(() => dataStore.userList);
onMounted(() => {
  dataStore.findEnumByCsName("IS_NOT");
  dataStore.findUserList();
  dataStore.findOrgTree();
});

// 表格配置项
const columns = reactive<ColumnProps<Performance>[]>([
  { type: "index", label: "序号", width: 85 },
  { prop: "userId", label: "姓名", width: 100, render: scope => userRender(scope, userList) },
  {
    prop: "orgId",
    label: "组织",
    width: 160,
    search: { el: "cascader", props: { filterable: true, showAllLevels: false, props: {} }, order: 2 },
    fieldNames: { label: "name", value: "_id" },
    enum: orgTree
  },
  {
    prop: "performanceType",
    label: "评估类型",
    search: { el: "select", props: { filterable: true } },
    enum: () => apiService.findClassify("performanceType"),
    fieldNames: { label: "name", value: "value" }
  },
  {
    prop: "performanceDate",
    label: "绩效周期",
    render: monthRender,
    search: {
      el: "date-picker",
      props: { type: "month" },
      order: 1,
      defaultValue: defaultDate,
      label: "绩效周期"
    }
  },
  {
    prop: "crossGroup",
    label: "跨组",
    enum: isOrNotList,
    search: { el: "select", props: { filterable: true } },
    render: scope => enumRender(scope, isOrNotList, "value"),
    fieldNames: { label: "name", value: "value" }
  },
  {
    prop: "crossRate",
    label: "评估占比",
    enum: () => apiService.findClassify("crossRate"),
    fieldNames: { label: "name", value: "value" }
  },
  {
    prop: "level",
    label: "等级",
    enum: () => apiService.findClassify("PERFORMANCE_LEVEL"),
    fieldNames: { label: "name", value: "value" }
  },
  { prop: "avgScore", label: "综合评分" },
  {
    prop: "state",
    label: "个人查看",
    render: scope => enumRender(scope, isOrNotList, "value"),
    fieldNames: { label: "name", value: "value" }
  },
  { prop: "operation", label: "操作", align: "left", fixed: "right", width: 180 }
]);

const getExcelConfig = (): ExportObj => {
  // 处理时间条件
  let newParams = JSON.parse(JSON.stringify(proTable.value?.totalParam));
  if (newParams.condition && newParams.condition.performanceDate) {
    let curDate = new Date(newParams.condition.performanceDate);
    let [year, month] = [curDate.getFullYear(), curDate.getMonth()];
    let startDate = new Date(year, month, 1);
    let endDate = new Date(year, month + 1, 0, 23, 59, 59);
    newParams.condition.performanceDate = { $gte: startDate, $lte: endDate };
  }
  if (newParams.condition.orgId && newParams.condition.orgId instanceof Array) {
    newParams.condition.orgId = newParams.condition.orgId[newParams.condition.orgId.length - 1];
  }
  return {
    params: newParams,
    tableName: initVar.tbName,
    keyPropName: "_id",
    enumTypes: ["performanceType", "IS_NOT", "crossRate", "PERFORMANCE_LEVEL"],
    tableConfigs: [
      { tableName: "users", fields: ["_id", "userName"] },
      { tableName: "orgs", fields: ["_id", "name"] }
    ],
    header: [
      { header: "序号", width: 6, ext: { prop: "index", type: ExportColType.INDEX } },
      {
        header: "姓名",
        width: 8,
        ext: { prop: "userId", type: ExportColType.TABLE, key: "users", label: "userName", value: "_id" }
      },
      { header: "组织", width: 15, ext: { prop: "orgId", type: ExportColType.TABLE, key: "orgs" } },
      { header: "评估类型", width: 8, ext: { prop: "performanceType", type: ExportColType.ENUM, key: "performanceType" } },
      {
        header: "绩效周期",
        width: 12,
        ext: { prop: "performanceDate", type: ExportColType.DATE_MONTH }
      },
      {
        header: "跨组",
        width: 15,
        ext: { prop: "crossGroup", type: ExportColType.ENUM, key: "IS_NOT" }
      },
      { header: "评估占比", width: 8, ext: { prop: "crossRate", type: ExportColType.ENUM, key: "crossRate" } },
      { header: "等级", width: 8, ext: { prop: "level", type: ExportColType.ENUM, key: "PERFORMANCE_LEVEL" } },
      { header: "综合评分", width: 8, ext: { prop: "avgScore", type: ExportColType.DEFAULT } },
      {
        header: "个人是否查看",
        width: 15,
        ext: { prop: "state", type: ExportColType.ENUM, key: "IS_NOT" }
      },
      {
        header: "是否面谈",
        width: 12,
        ext: { prop: "chat_state", type: ExportColType.ENUM, key: "IS_NOT" }
      },
      { header: "评估内容", width: 50, ext: { prop: "summary", type: ExportColType.DEFAULT } }
    ]
  };
};

// 导出数据
const downloadFile = async () => {
  ElMessageBox.confirm("确认导出数据?", "温馨提示", { type: "warning" }).then(() =>
    useDownload(
      apiService.commonExport,
      `绩效评估清单-${useDateFormat(new Date(), "YYYY-MM-DD").value}`,
      "",
      getExcelConfig(),
      false
    )
  );
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof EvaluateDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<Performance> = {}) => {
  const params = {
    title,
    tbName: initVar.tbName,
    isView: title === "查看",
    row: row,
    api: title.indexOf("新增") !== -1 ? apiService.save : title === "编辑" ? apiService.updateById : undefined,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};
</script>
